package com.jolink.omiis.wechat.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 媒体处理
 * 用于将腾讯的amr转换为mp3格式
 * 
 * 注：1、微信server部署到Linux平台，需要将根目录下的./ffmpeg/linux/ffmpeg 同时部署到Linux服务器；
 *    2、添加可执行权限，chmod 755 ./ffmpeg
 * 
 * @author WangYanqing
 *
 */
public class FFMpegTransfer {

	private static Logger logger = LoggerFactory.getLogger(FFMpegTransfer.class);
	/**
	 * 可执行 bin
	 */
	private static String FFMPEG_EXECUTABLE_BIN = "ffmpeg";
	private static String OS_NAME = "os.name";

	/**
	 * amr 格式转 mp3格式
	 * 
	 * @param src
	 * @param dst
	 * @return
	 */
	public static Map<String, String> transfer(String src, String dst) {
		long t1 = System.currentTimeMillis();
		logger.info("开始音频转制......");
		File srcFile = new File(src);
		if (!srcFile.exists()) {
			throw new RuntimeException("源文件：" + src + "不存在！");
		}
		File dstFile = new File(dst);
		if (dstFile.exists()) {
			logger.info("目标文件已存在，删除文件：{}，执行结果：{}。", dstFile.getAbsolutePath(), dstFile.delete());
		}
		List<String> commands = new ArrayList<>();
		String os_name = System.getProperty(OS_NAME);
		logger.info("音频转换运行的平台：{}。", os_name);
		if (os_name.startsWith("Windows")) {
			logger.warn("windows平台暂不支持。");
		} else if (os_name.startsWith("Linux")) {
			commands.add("./ffmpeg/linux/" + FFMPEG_EXECUTABLE_BIN);
			commands.add("-i");
			commands.add(src);
			commands.add(dst);
		} else if (os_name.startsWith("Mac")) {
			commands.add("./ffmpeg/mac/" + FFMPEG_EXECUTABLE_BIN);
			commands.add("-i");
			commands.add(src);
			commands.add(dst);
		}
		String cmdPath = commands.get(0);
		logger.info("可执行文件路径：{}。", cmdPath);
		if (!new File(cmdPath).exists()) {
			throw new RuntimeException("可执行文件：" + "不存在！");
		}
		InputStream is = null;
		BufferedReader br = null;
		Map<String, String> mediaInfo = new HashMap<String, String>();
		try {
			ProcessBuilder pb = new ProcessBuilder();
			pb.redirectErrorStream(true);
			pb = pb.command(commands);
			Process process = pb.start();
			is = process.getInputStream();
			br = new BufferedReader(new InputStreamReader(is));
			mediaInfo.put("fileName", dstFile.getName());
			String line = null;
			while ((line = br.readLine()) != null) {
				logger.info(line);
				if (line.startsWith("size=")) {
					logger.info("读取音频长度");
					int endIndex = line.indexOf("bitrate");
					int startIndex = line.indexOf("time");
					String duration = line.substring(startIndex + 5, endIndex);
					String[] splits = duration.split("[:|.]+");
					logger.info("截取到的音频长度内容：{}。", Arrays.toString(splits));
					int h = Integer.parseInt(splits[0]) * 3600;
					int m = Integer.parseInt(splits[1]) * 60;
					int s = Integer.parseInt(splits[2]);
					float ms = Float.parseFloat(splits[3]) / 1000;
					mediaInfo.put("duration", String.valueOf(h + m + s + ms));
				}
			}
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		} finally {
			if (is != null) {
				try {
					is.close();
					br.close();
				} catch (IOException e) {
					logger.error(e.getMessage(), e);
				}
			}
		}
		long t2 = System.currentTimeMillis();
		logger.info("转换音频格式完成，音频信息：{}，耗时：{}毫秒。", mediaInfo, (t2 - t1));
		return mediaInfo;
	}

}
